import { NextResponse } from "next/server";

const isAuthenticated = async (req) => {
  const authHeader =
    req.headers.get("authorization") || req.headers.get("Authorization");
  if (!authHeader) {
    return false;
  }
  const [username, password] = Buffer.from(authHeader.split(" ")[1], "base64")
    .toString()
    .split(":");
  return username === "admin" && password === "123456";
};

// 每个函数或者每个页面调用前都会执行
export const middleware = async (req) => {
  if ((await isAuthenticated(req)) === false) {
    return new NextResponse("Unauthorized", {
      status: 401,
      headers: {
        "WWW-Authenticate": "Basic",
      },
    });
  }
};

export const config = {
  matcher: "/admin/:path*",
};
